import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {
  View,
  TouchableOpacity,
  StyleSheet,
  Image,
  Text,
  ActivityIndicator,
  Animated,
  Easing,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import {Colors} from '../styles/common';
import {CachedImage} from 'react-native-img-cache';

const styles = StyleSheet.create({
  normalBtn: {
    backgroundColor: '#875520',
    height: 44,
    borderRadius: 22,
    justifyContent: 'center',
    marginTop: 20,
  },
  normalBtnTitle: {
    fontSize: 17,
    fontWeight: '400',
    textAlign: 'center',
    color: '#fff',
  },
  btnDefaultStyle: {
    width: 20,
    height: 20,
    alignItems: 'center',
    justifyContent: 'center',
    // backgroundColor: 'blue',
  },
  backgroundImageStyle: {
    width: 20,
    height: 20,
  },
  titleStyle: {
    color: 'white',
    fontSize: 14,
    marginTop: 2,
    width: '100%',
    textAlign: 'center',
  },
  containerStyle: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    paddingLeft: 5,
    paddingRight: 5,
  },
});
class TextButton extends Component {
  static propTypes = {
    onPress: PropTypes.func.isRequired,
    text: PropTypes.any.isRequired,
    isDisabled: PropTypes.bool,
    buttonStyle: PropTypes.any,
    textStyle: PropTypes.object,
  };

  render() {
    const {buttonStyle, isDisabled, onPress, text, textStyle} = this.props;
    return (
      <TouchableOpacity
        style={[styles.normalBtn, buttonStyle]}
        activeOpacity={0.6}
        disabled={isDisabled}
        onPress={onPress}>
        <Text style={[styles.normalBtnTitle, textStyle]} numberOfLines={1}>
          {text}
        </Text>
      </TouchableOpacity>
    );
  }
}

class ImageTitleButton extends Component {
  static propTypes = {
    source: PropTypes.number.isRequired,
    onPress: PropTypes.func,
    title: PropTypes.string,
  };

  render() {
    const {
      btnStyle,
      onPress,
      imageStyle,
      source,
      title,
      titleStyle,
      containerStyle,
    } = this.props;
    return (
      <View style={[styles.containerStyle, containerStyle]}>
        <TouchableOpacity
          style={[styles.btnDefaultStyle, btnStyle]}
          onPress={onPress}>
          <Image
            style={[styles.backgroundImageStyle, imageStyle]}
            source={source}
          />
        </TouchableOpacity>
        <Text style={[styles.titleStyle, titleStyle]}>{title}</Text>
      </View>
    );
  }
}

class ImageButton extends Component {
  static propTypes = {
    source: PropTypes.any.isRequired,
    onPress: PropTypes.func,
    imageStyle: PropTypes.object,
  };

  render() {
    const {btnStyle, onPress, imageStyle, source} = this.props;
    return (
      <TouchableOpacity
        style={[styles.btnDefaultStyle, btnStyle]}
        onPress={onPress}>
        <CachedImage
          cache={'force-cache'}
          style={[styles.backgroundImageStyle, imageStyle]}
          source={source}
        />
      </TouchableOpacity>
    );
  }
}

class LinearButton extends Component {
  static propTypes = {
    onPress: PropTypes.func.isRequired,
    text: PropTypes.any.isRequired,
    isDisabled: PropTypes.bool,
    buttonStyle: PropTypes.any,
    textStyle: PropTypes.object,
    loading: PropTypes.bool,
  };

  static defaultProps = {
    loading: false,
  };

  constructor(props) {
    super(props);

    this.state = {
      rotateVal: new Animated.Value(0),
    };
  }

  componentWillUnmount() {
    if (this.animationLoading) {
      Animated.loop(this.animationLoading).stop;
    }
  }

  componentDidUpdate(prevProps) {
    // console.log('=======');
    // console.log(this.props);
    if (this.props.loading == true) {
      // console.log('执行动画');
      this.animationLoading = Animated.timing(
        this.state.rotateVal, // 初始值
        {
          toValue: 360, // 终点值
          useNativeDriver: true,
          duration: 1500,
          easing: Easing.linear, // 这里使用匀速曲线，详见RN-api-Easing
        },
      );
      Animated.loop(this.animationLoading).start(); // 开始动画
    } else {
      this.state.rotateVal = new Animated.Value(0);
    }
  }

  pressBtn = () => {
    if (!this.props.loading) {
      this.props.onPress();
    }
  };

  render() {
    const {
      buttonStyle,
      isDisabled,
      onPress,
      text,
      textStyle,
      loading,
    } = this.props;

    return (
      <LinearGradient
        start={{x: 0, y: 1}}
        end={{x: 1, y: 1}}
        colors={isDisabled ? ['#B6B6B6', '#B6B6B6'] : ['#CE18EC', '#6601F5']}
        style={[styles.normalBtn, buttonStyle]}>
        <TouchableOpacity
          style={{flex: 1, justifyContent: 'center'}}
          activeOpacity={0.6}
          disabled={isDisabled}
          onPress={this.pressBtn}>
          {loading ? (
            <Animated.Image
              style={{
                width: 20,
                height: 20,
                alignSelf: 'center',
                transform: [
                  {
                    rotate: this.state.rotateVal.interpolate({
                      inputRange: [0, 360],
                      outputRange: ['0deg', '360deg'],
                    }),
                  },
                ],
              }}
              source={require('../assets/common/btn_loading_2.png')}></Animated.Image>
          ) : (
            <Text style={[styles.normalBtnTitle, textStyle]} numberOfLines={1}>
              {text}
            </Text>
          )}
        </TouchableOpacity>
      </LinearGradient>
    );
  }
}

class LinearBoardButton extends Component {
  static propTypes = {
    onPress: PropTypes.func.isRequired,
    text: PropTypes.any.isRequired,
    isDisabled: PropTypes.bool,
    buttonStyle: PropTypes.object,
    textStyle: PropTypes.object,
    loading: PropTypes.bool,
  };

  static defaultProps = {
    loading: false,
  };

  constructor(props) {
    super(props);

    this.state = {
      rotateVal: new Animated.Value(0),
    };
  }

  componentWillUnmount() {
    if (this.animationLoading) {
      Animated.loop(this.animationLoading).stop;
    }
  }

  componentDidUpdate(prevProps) {
    if (this.props.loading == true) {
      // console.log('执行动画');
      this.animationLoading = Animated.timing(
        this.state.rotateVal, // 初始值
        {
          toValue: 360, // 终点值
          useNativeDriver: true,
          duration: 1500,
          easing: Easing.linear, // 这里使用匀速曲线，详见RN-api-Easing
        },
      );
      Animated.loop(this.animationLoading).start(); // 开始动画
    } else {
      this.state.rotateVal = new Animated.Value(0);
    }
  }

  pressBtn = () => {
    if (!this.props.loading) {
      this.props.onPress();
    }
  };

  render() {
    const {
      buttonStyle,
      isDisabled,
      onPress,
      text,
      textStyle,
      loading,
    } = this.props;
    return (
      <LinearGradient
        start={{x: 0, y: 1}}
        end={{x: 1, y: 1}}
        colors={isDisabled ? ['#B6B6B6', '#B6B6B6'] : ['#CE18EC', '#6601F5']}
        style={[styles.normalBtn, buttonStyle, {padding: 2}]}>
        <TouchableOpacity
          style={{
            flex: 1,
            // width: (buttonStyle.width || styles.normalBtn.width) - 4,
            // height: (buttonStyle.height || styles.normalBtn.height) - 4,
            justifyContent: 'center',
            backgroundColor: 'white',
            borderRadius:
              ((buttonStyle.height || styles.normalBtn.height) - 4) / 2,
          }}
          activeOpacity={0.6}
          disabled={isDisabled}
          onPress={this.pressBtn}>
          {loading ? (
            <Animated.Image
              style={{
                width: 20,
                height: 20,
                alignSelf: 'center',
                transform: [
                  {
                    rotate: this.state.rotateVal.interpolate({
                      inputRange: [0, 360],
                      outputRange: ['0deg', '360deg'],
                    }),
                  },
                ],
              }}
              source={require('../assets/common/btn_loading_purple.png')}></Animated.Image>
          ) : (
            <Text
              style={[styles.normalBtnTitle, textStyle, {color: '#C817EC'}]}
              numberOfLines={1}>
              {text}
            </Text>
          )}
        </TouchableOpacity>
      </LinearGradient>
    );
  }
}

export {
  TextButton,
  ImageButton,
  LinearButton,
  LinearBoardButton,
  ImageTitleButton,
};
